package com.innovation.chengzhangriji.ui.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.ChZhRJApplication;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Flavors;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BaseRequest;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.model.UITimeline;
import com.innovation.chengzhangriji.ui.model.UITimelineMilestone;
import com.innovation.chengzhangriji.ui.model.UITimelinePhoto;
import com.innovation.chengzhangriji.ui.model.UITimelineText;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.TimelineAudioViewHolder;
import com.innovation.chengzhangriji.ui.widget.TimelinePhotoViewHolder;
import com.innovation.chengzhangriji.ui.widget.TimelineVideoViewHolder;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.innovation.chengzhangriji.util.WXUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orhanobut.dialogplus.*;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

public class DTAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements DTPhotoHolder.OnClickPhotoListener, DTAudioHolder.AudioListener, DTVideoHolder.OnClickVideoListener, DTProgressHolder.OnClickErrorListener, DTHolder.OnClickCommentListener, View.OnClickListener {

    private Context context;

    private int mPosition;

    private Dialog mDialog;

    CuteTextView textShare;

    CuteTextView textDelete;

    View layoutDriver, layoutDriver1, layoutDriver2;

    CuteTextView textCopy, textLike, textComment;

    private static final float EDGE = 150.0f;

    public DTAdapter(DTAdapterAgent agent, Context context) {
        this.agent = agent;
        this.context = context;

        mDialog = new Dialog(context, R.style.Theme_ChZhRJ_Dialog_TimeLine);
        mDialog.setContentView(R.layout.option_layout_2);
        mDialog.getWindow().setGravity(Gravity.TOP | Gravity.RIGHT);
        textShare = (CuteTextView) mDialog.getWindow().getDecorView().findViewById(R.id.text_share);
        textShare.setOnClickListener(this);
        layoutDriver = mDialog.getWindow().getDecorView().findViewById(R.id.layout_driver);
        layoutDriver1 = mDialog.getWindow().getDecorView().findViewById(R.id.layout_driver_1);
        layoutDriver2 = mDialog.getWindow().getDecorView().findViewById(R.id.layout_driver_2);
        textDelete = (CuteTextView) mDialog.getWindow().getDecorView().findViewById(R.id.text_delete);
        textDelete.setOnClickListener(this);
        textCopy = (CuteTextView) mDialog.getWindow().getDecorView().findViewById(R.id.text_copy);
        textCopy.setOnClickListener(this);
        textLike = (CuteTextView) mDialog.getWindow().getDecorView().findViewById(R.id.btn_like);
        textLike.setOnClickListener(this);
        textComment = (CuteTextView) mDialog.getWindow().getDecorView().findViewById(R.id.btn_comment);
        textComment.setOnClickListener(this);
        mTencent = Tencent.createInstance(mAppid, context);
    }

    private boolean end;

    private boolean error;

    public static final int TEXT = 0;

    public static final int PHOTO = 1;

    public static final int AUDIO = 2;

    public static final int VIDEO = 3;

    public static final int MILESTONE = 4;

    private static final int LOAD_MORE = 5;
    
    private DTAdapterAgent agent;

    //qq分享
    private static Tencent mTencent;
    private final static String mAppid = "" + 1104215150;//正式

    public static interface DTAdapterAgent {
        public void onClickPhoto(int position1, int position2);
        public void onClickAudio(int position);
        public void downloadAudio(int position);
        public void onClickVideo(int position);

        // 数据长度
        public int length();
        // 发表人
        public String userName(int position);
        // 发表人头像
        public String userUrl(int position);
        // 发表日期
        public long time(int position);
        // 是否是显示评论区域
        public boolean showBottom(int position);
        // 是否显示赞
        public boolean showLike(int position);
        // 设置评论列表
        public ArrayList<String> likeList(int position);
        // 是否显示评论
        public boolean showComment(int position);
        // 是否显示评论
        public ArrayList<CommentModel> commentList(int position);
        // 文本日记内容
        public String text(int position);
        // 照片日记的主题
        public String photoLabel(int position);
        // 照片日记的内容
        public String photoContent(int position);
        // 照片列表
        public String[] photoUrl(int position);
        // 音频的长度
        public int audioLength(int position);
        // 是否播放音频
        public boolean audioPlay(int position);
        // 视频截图
        public String thumbnailUrl(int position);
        // 第一次的内容
        public String milestone(int position);
        // 宝宝的大小
        public String age(int position);
        // 日记的类型
        public int type(int position);
        // 日记的编号
        public String diaryId(int position);
        // 移除日记
        public void removeDiary(int position);
        // 照片主题
        public String theme(int position);
        // 停止播放
        public void stopPlayback();
        // 发布人
        public String userId(int position);
        // 发表评论
        public void sendComment(int position);
        public void sendComment(int pos1, int pos2);
        // 赞/取消赞
        public void sendPraise(int position);
        // 是否赞
        public boolean isLike(int position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_discover_timeline, parent, false);
        RecyclerView.ViewHolder holder = null;
        switch (viewType) {
            case TEXT:
                holder = new DTTextHolder(view);
                break;
            case PHOTO:
                holder = new DTPhotoHolder(view);
                ((DTPhotoHolder) holder).setOnClickPhotoListener(this);
                break;
            case AUDIO:
                holder = new DTAudioHolder(view);
                ((DTAudioHolder) holder).setAudioListener(this);
                break;
            case VIDEO:
                holder = new DTVideoHolder(view);
                ((DTVideoHolder) holder).setOnClickVideoListener(this);
                break;
            case MILESTONE:
                holder = new DTMilestoneViewHolder(view);
                break;
            case LOAD_MORE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dt_progress, parent, false);
                holder = new DTProgressHolder(view);
                ((DTProgressHolder) holder).setOnClickErrorListener(this);
                return holder;
        }
        if(holder != null) {
            ((DTHolder)holder).setOnClickCommentListener(this);
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == LOAD_MORE) {
            ((DTProgressHolder) holder).setError(error);
        } else {
            ((DTHolder) holder).setUserName(agent.userName(position));
            ((DTHolder) holder).setImageUserHeadUrl(agent.userUrl(position));
            ((DTHolder) holder).setDate(agent.time(position));
            ((DTHolder) holder).setAge(agent.age(position));
            ((DTHolder) holder).setCommentLayoutIsVisible(agent.showBottom(position));
            ((DTHolder) holder).setLikeIsVisible(agent.showLike(position));
            ((DTHolder) holder).setCommentIsVisible(agent.showComment(position));
            ((DTHolder) holder).setLikeList(agent.likeList(position));
            ((DTHolder) holder).setCommentList(context, agent.commentList(position));
            switch (getItemViewType(position)) {
                case TEXT:
                    ((DTTextHolder) holder).setText(agent.text(position));
                    break;
                case PHOTO:
                    ((DTPhotoHolder) holder).setPhotoLabel(agent.photoLabel(position));
                    ((DTPhotoHolder) holder).setPhotoContent(agent.photoContent(position));
                    ((DTPhotoHolder) holder).setPhotoUrl(agent.photoUrl(position));
                    break;
                case AUDIO:
                    ((DTAudioHolder) holder).setAudioLength(agent.audioLength(position));
                    ((DTAudioHolder) holder).setAudioPlay(agent.audioPlay(position));
                    ((DTAudioHolder) holder).downloadAudio();
                    break;
                case VIDEO:
                    ((DTVideoHolder) holder).setVideoThumbnailUrl(agent.thumbnailUrl(position));
                    break;
                case MILESTONE:
                    ((DTMilestoneViewHolder) holder).setMilestone(agent.milestone(position));
                    break;
            }
            if(position == 0) {
                holder.itemView.setPadding(0, (int) ChZhRJUtils.dp2px(5, holder.itemView.getResources().getDisplayMetrics()), 0, 0);
                ((DTHolder)holder).setDateIsVisible(true);
                ((DTHolder)holder).setTopLineVisible(false);
            } else {
                holder.itemView.setPadding(0, 0, 0, 0);
                ((DTHolder)holder).setTopLineVisible(true);
                Date current = new Date(agent.time(position));
                Date prev = new Date(agent.time(position - 1));
                if(current.getYear() != prev.getYear() || current.getMonth() != prev.getMonth() || current.getDate() != prev.getDate()) {
                    // 不是同一天
                    ((DTHolder)holder).setDateIsVisible(true);
                } else {
                    ((DTHolder)holder).setDateIsVisible(false);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_share:
                // 判断是否已经上传完成
                if (DatabaseManager.getInstance(context).queryRemoteExist(agent.diaryId(mPosition))) {
                    mDialog.dismiss();
                    openShareDialog();
                } else {
                    Toast.makeText(context, "日记正在上传,请稍后分享!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.text_delete:
                mDialog.dismiss();
                openDeleteDialog();
                break;
            case R.id.text_copy:
                mDialog.dismiss();
                copyText();
                break;
            case R.id.btn_comment:
                mDialog.dismiss();
                agent.sendComment(mPosition);
                break;
            case R.id.btn_like:
                mDialog.dismiss();
                agent.sendPraise(mPosition);
                break;
        }
    }

    private void openDeleteDialog() {
        new AlertDialog.Builder(context)
                .setTitle("确认要删除么?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 更新界面
                        DatabaseManager.getInstance(context).deleteUnSyncTimeline(agent.diaryId(mPosition));
                        agent.stopPlayback();
                        agent.removeDiary(mPosition);
                        Config.startDeleteTimelineService(context);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void openShareDialog() {
        DialogPlus dialog = new DialogPlus.Builder(context)
                .setAdapter(new WXAdapter())
                .setGravity(Gravity.BOTTOM)
                .setContentHolder(new GridHolder(3))
                .setCancelable(true)
                .setOnItemClickListener(new com.orhanobut.dialogplus.OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        switch (position) {
                            case 0:
                                sendToWXSession(mPosition);
                                dialog.dismiss();
                                break;
                            case 1:
                                sendToWXTimeline(mPosition);
                                dialog.dismiss();
                                break;
                            case 2:
//                                Toast.makeText(context,"22",Toast.LENGTH_SHORT).show();
                                qqShare(mPosition);
                                dialog.dismiss();
                                break;
                        }
                    }
                })
                .create();
        dialog.show();
    }
    private void qqShare(int position) {
        String image_path="";
        String uuid = (Flavors.URL_TYPE == 3? "1_":"0_") + agent.diaryId(position);
        if (agent.photoUrl(position).length >0){
            image_path = agent.photoUrl(position)[0];
        }else{
            image_path= "https://iemylifestorageint.blob.core.chinacloudapi.cn/app/logo/IEMyLife_logo.png";
        }
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, buildDescription(position));
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, buildDescription(position));
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, BaseRequest.PATH + "/WXShare/Share/" + uuid);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "");
        mTencent.shareToQQ((Activity) context, params, new BaseUiListener());
    }
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            if (null == response) {
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                return;
            }
            doComplete((JSONObject) response);
        }
        protected void doComplete(JSONObject values) {
        }
        @Override
        public void onError(UiError e) {
        }
        @Override
        public void onCancel() {
        }
    }
    private void sendToWXSession(int position) {
        IWXAPI api = ((ChZhRJApplication) context.getApplicationContext()).getWeiXinApi();
        String uuid = (Flavors.URL_TYPE == 3? "1_":"0_") + agent.diaryId(position);
        switch (getItemViewType(position)) {
            case TEXT:
                WXUtils.sendTextToWXSession(api, uuid, "成长日记,可以随身携带的日记本,给宝宝制定的专属成人礼", agent.text(position));
                break;
            case PHOTO:
                if(agent.photoUrl(position)[0] == null) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                String thumbUrl = null;
                if(agent.photoUrl(position)[0].startsWith("/")) {
                    thumbUrl = agent.photoUrl(position)[0];
                } else {
                    thumbUrl = ImageLoader.getInstance().getDiskCache().get(agent.photoUrl(position)[0]).getPath();
                    if (thumbUrl == null || !new File(thumbUrl).exists()) {
                        thumbUrl = ImageLoader.getInstance().getDiskCache().get(Config.createSizeUrl(agent.photoUrl(position)[0], 480)).getPath();
                    }
                }
                if(thumbUrl == null || !new File(thumbUrl).exists()) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                Bitmap thumb = decodeFile(thumbUrl);
                WXUtils.sendUrlToWXSession(api, uuid, "成长日记,可以随身携带的日记本,给宝宝制定的专属成人礼", buildDescription(position), BaseRequest.PATH + "/wxshare/share/" + uuid, thumb);
                break;
            case UITimeline.TYPE_VIDEO:
                if(agent.thumbnailUrl(position) == null) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                String thumbnailUrl = null;
                if(agent.thumbnailUrl(position).startsWith("/")) {
                    thumbnailUrl = agent.thumbnailUrl(position);
                } else {
                    thumbnailUrl = ImageLoader.getInstance().getDiskCache().get(agent.thumbnailUrl(position)).getPath();
                    if (thumbnailUrl == null || !new File(thumbnailUrl).exists()) {
                        thumbnailUrl = ImageLoader.getInstance().getDiskCache().get(Config.createSizeUrl(agent.thumbnailUrl(position), 480)).getPath();
                    }
                }
                if(thumbnailUrl == null || !new File(thumbnailUrl).exists()) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                Bitmap thumbBmp = decodeFile(thumbnailUrl);
                WXUtils.sendUrlToWXTimeline(api, uuid, buildDescription(position), BaseRequest.PATH + "/WXShare/Share/" + uuid, thumbBmp);
                break;
            case MILESTONE:
                WXUtils.sendTextToWXSession(api, uuid, "成长日记,可以随身携带的日记本,给宝宝制定的专属成人礼", agent.milestone(position));
                break;
        }
    }

    private String buildDescription(int position) {
        String theme = agent.theme(position);
        if (TextUtils.isEmpty(theme)) {
            theme = "";
        } else {
            theme = "(" + theme + ")";
        }
        String text = agent.text(position);
        if (TextUtils.isEmpty(text)) {
            text = "我给宝宝记录了一篇成长日记,大家快来围观吧!";
        }
        return theme + text;
    }

    private class WXAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            View view = convertView;

            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.item_wx, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.textView = (CuteTextView) view.findViewById(R.id.text_view);
                viewHolder.imageView = (ImageView) view.findViewById(R.id.image_view);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            switch (position) {
                case 0:
                    viewHolder.textView.setText("分享到微信");
                    viewHolder.imageView.setImageResource(R.drawable.icon_session_share);
                    break;
                case 1:
                    viewHolder.textView.setText("分享到朋友圈");
                    viewHolder.imageView.setImageResource(R.drawable.icon_timeline_share);
                    break;
                case 2:
                    viewHolder.textView.setText("分享到QQ");
                    viewHolder.imageView.setImageResource(R.drawable.icon_qq_friend_share);
                    break;
            }

            return view;
        }

        class ViewHolder {
            CuteTextView textView;
            ImageView imageView;
        }
    }

    private void sendToWXTimeline(int position) {
        IWXAPI api = ((ChZhRJApplication) context.getApplicationContext()).getWeiXinApi();
        String uuid = (Flavors.URL_TYPE == 3? "1_":"0_") + agent.diaryId(position);
        switch (getItemViewType(position)) {
            case UITimeline.TYPE_TEXT:
                WXUtils.sendTextToWXTimeline(api, uuid, "成长日记,可以随身携带的日记本,给宝宝制定的专属成人礼", agent.text(position));
                break;
            case UITimeline.TYPE_PHOTO:
                if(agent.photoUrl(position)[0] == null) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                String thumbUrl = null;
                if(agent.photoUrl(position)[0].startsWith("/")) {
                    thumbUrl = agent.photoUrl(position)[0];
                } else {
                    thumbUrl = ImageLoader.getInstance().getDiskCache().get(agent.photoUrl(position)[0]).getPath();
                    if (thumbUrl == null || !new File(thumbUrl).exists()) {
                        thumbUrl = ImageLoader.getInstance().getDiskCache().get(Config.createSizeUrl(agent.photoUrl(position)[0], 480)).getPath();
                    }
                }
                if(thumbUrl == null || !new File(thumbUrl).exists()) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                Bitmap thumb = decodeFile(thumbUrl);
                WXUtils.sendUrlToWXTimeline(api, uuid, buildDescription(position), BaseRequest.PATH + "/WXShare/Share/" + uuid, thumb);
                break;
            case UITimeline.TYPE_VIDEO:
                if(agent.thumbnailUrl(position) == null) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                String thumbnailUrl = null;
                if(agent.thumbnailUrl(position).startsWith("/")) {
                    thumbnailUrl = agent.thumbnailUrl(position);
                } else {
                    thumbnailUrl = ImageLoader.getInstance().getDiskCache().get(agent.thumbnailUrl(position)).getPath();
                    if (thumbnailUrl == null || !new File(thumbnailUrl).exists()) {
                        thumbnailUrl = ImageLoader.getInstance().getDiskCache().get(Config.createSizeUrl(agent.thumbnailUrl(position), 480)).getPath();
                    }
                }
                if(thumbnailUrl == null || !new File(thumbnailUrl).exists()) {
                    Toast.makeText(context, "图片不存在，分享失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                Bitmap thumbBmp = decodeFile(thumbnailUrl);
                WXUtils.sendUrlToWXTimeline(api, uuid, buildDescription(position), BaseRequest.PATH + "/WXShare/Share/" + uuid, thumbBmp);
                break;
            case UITimeline.TYPE_MILESTONE:
                WXUtils.sendTextToWXTimeline(api, uuid, "成长日记,可以随身携带的日记本,给宝宝制定的专属成人礼", agent.milestone(position));
                break;
        }
    }

    private Bitmap decodeFile(String path) {
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, decodeOptions);
        int width = decodeOptions.outWidth;
        int height = decodeOptions.outHeight;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        int size = 1;
        if (width > EDGE || height > EDGE) {
            int wRatio = Math.round(width / EDGE);
            int hRation = Math.round(height / EDGE);
            size = wRatio < hRation ? wRatio : hRation;
        }
        options.inSampleSize = size;
        return BitmapFactory.decodeFile(path, options);
    }

    // 复制文本
    public void copyText() {
        String text = "";
        switch(getItemViewType(mPosition)) {
            case UITimeline.TYPE_TEXT:
                text = agent.text(mPosition);
                break;
            case UITimeline.TYPE_PHOTO:
                text = agent.text(mPosition);
                break;
            case UITimeline.TYPE_MILESTONE:
                text = agent.milestone(mPosition);
                break;
        }
        if(!TextUtils.isEmpty(text)) {
            ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(text);
        }
    }

    @Override
    public void onClickCommentPosition(DTHolder holder, int position) {
        agent.sendComment(holder.getLayoutPosition(), position);
    }

    @Override
    public void showCommentDialog(DTHolder holder) {
        mPosition = holder.getLayoutPosition();

        // 是显示赞还是取消赞
        if(agent.isLike(mPosition)) {
            textLike.setText(context.getString(R.string.unlike));
        } else {
            textLike.setText(context.getString(R.string.like));
        }

        // 判断是否有权限分享和删除
        LoginInfo loginInfo = Config.getLoginInfo(context);
        if (loginInfo == null) {
            return;
        }
        // 默认显示
        textShare.setVisibility(View.VISIBLE);
        layoutDriver1.setVisibility(View.VISIBLE);
        textDelete.setVisibility(View.VISIBLE);
        layoutDriver2.setVisibility(View.VISIBLE);

        if (holder instanceof DTAudioHolder || holder instanceof DTVideoHolder) {
//        if (holder instanceof DTAudioHolder) {
            textShare.setVisibility(View.GONE);
            layoutDriver1.setVisibility(View.GONE);
            textCopy.setVisibility(View.GONE);
            layoutDriver2.setVisibility(View.GONE);
        } else {
            textShare.setVisibility(View.VISIBLE);
            layoutDriver1.setVisibility(View.VISIBLE);
            textCopy.setVisibility(View.VISIBLE);
            layoutDriver2.setVisibility(View.VISIBLE);
            if(holder instanceof DTPhotoHolder && TextUtils.isEmpty(agent.text(mPosition))) {
                textCopy.setVisibility(View.GONE);
                layoutDriver2.setVisibility(View.GONE);
            }
        }

        String userId = loginInfo.getUserID();
        int babyId = loginInfo.getBabyID();
        Baby baby = DatabaseManager.getInstance(context).queryBaby(userId, babyId);
        if (baby == null) {
            textShare.setVisibility(View.GONE);
            layoutDriver1.setVisibility(View.GONE);
            textDelete.setVisibility(View.GONE);
            layoutDriver2.setVisibility(View.GONE);
            // return;
        }
        if (!agent.userId(mPosition).equals(userId)) {
            textShare.setVisibility(View.GONE);
            layoutDriver1.setVisibility(View.GONE);
            textDelete.setVisibility(View.GONE);
            layoutDriver2.setVisibility(View.GONE);
            // return;
        }
        if(textCopy.getVisibility() == View.GONE && textShare.getVisibility() == View.GONE && textDelete.getVisibility() == View.GONE) {
            layoutDriver.setVisibility(View.GONE);
        } else {
            layoutDriver.setVisibility(View.VISIBLE);
        }
        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        lp.x = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36.5f, dm);
        lp.y = (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 157, dm) + holder.itemView.getY() + holder.getY());
        dialogWindow.setAttributes(lp);
        mDialog.show();
    }

    // 评论
    public static class CommentModel {

        private String userName1;

        private String userName2;

        private String content;

        public String getUserName1() {
            return userName1;
        }

        public void setUserName1(String userName1) {
            this.userName1 = userName1;
        }

        public String getUserName2() {
            return userName2;
        }

        public void setUserName2(String userName2) {
            this.userName2 = userName2;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }

    @Override
    public void onClickPhoto(DTPhotoHolder holder, int position) {
        agent.onClickPhoto(holder.getLayoutPosition(), position);
    }

    @Override
    public void onClickAudio(DTAudioHolder holder) {
        agent.onClickAudio(holder.getLayoutPosition());
    }

    @Override
    public void downloadAudio(DTAudioHolder holder) {
        agent.downloadAudio(holder.getLayoutPosition());
    }

    @Override
    public void onClickVideo(DTVideoHolder holder) {
        agent.onClickVideo(holder.getLayoutPosition());
    }

    @Override
    public void onClickError() {

    }

    public boolean isEnd() {
        return end;
    }

    public void setEnd(boolean end) {
        this.end = end;
    }

    public boolean isError() {
        return error;
    }

    public void setError(boolean error) {
        this.error = error;
    }

    @Override
    public int getItemViewType(int position) {
        if (end) {
            return agent.type(position);
        } else {
            if (position == agent.length()) {
                return LOAD_MORE;
            } else {
                return agent.type(position);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (agent.length() == 0) {
            end = true;
        }
        if (end) {
            return agent.length();
        } else {
            return agent.length() + 1;
        }
    }
}
